package com.ledi.guns.core.util.baiduUtil;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ledi.guns.core.util.baiduUtil.define.ActionMap;
import com.ledi.guns.core.util.baiduUtil.define.AppInfo;
import com.ledi.guns.core.util.baiduUtil.define.BaseState;
import com.ledi.guns.core.util.baiduUtil.define.State;
import com.ledi.guns.core.util.baiduUtil.hunter.FileManager;
import com.ledi.guns.core.util.baiduUtil.hunter.ImageHunter;
import com.ledi.guns.core.util.baiduUtil.upload.Uploader;

public class ActionEnter {

	private HttpServletRequest request = null;

	private String actionType = null;

	private ConfigManager configManager = null;

	public ActionEnter(ConfigManager configManager) {

		this.configManager = configManager;
	}

	public String exec(HttpServletRequest request) {

		this.request = request;
		actionType = request.getParameter("action");
		String callbackName = this.request.getParameter("callback");

		if (callbackName != null) {

			if (!validCallbackName(callbackName)) {
				return new BaseState(false, AppInfo.ILLEGAL).toJSONString();
			}

			return callbackName + "(" + invoke() + ");";

		} else {
			return invoke();
		}

	}

	public String invoke() {

		if (actionType == null || !ActionMap.mapping.containsKey(actionType)) {
			return new BaseState(false, AppInfo.INVALID_ACTION).toJSONString();
		}

		if (configManager == null || !configManager.valid()) {
			return new BaseState(false, AppInfo.CONFIG_ERROR).toJSONString();
		}

		State state = null;

		int actionCode = ActionMap.getType(actionType);

		Map<String, Object> conf = null;

		switch (actionCode) {

			case ActionMap.CONFIG:
				return configManager.getAllConfig().toString();

			case ActionMap.UPLOAD_IMAGE:
			case ActionMap.UPLOAD_SCRAWL:
			case ActionMap.UPLOAD_VIDEO:
			case ActionMap.UPLOAD_FILE:
				conf = configManager.getConfig(actionCode);
				state = new Uploader(request, conf).doExec();
				break;

			case ActionMap.CATCH_IMAGE:
				conf = configManager.getConfig(actionCode);
				String[] list = request.getParameterValues((String) conf.get("fieldName"));
				state = new ImageHunter(conf).capture(list);
				break;

			case ActionMap.LIST_IMAGE:
			case ActionMap.LIST_FILE:
				conf = configManager.getConfig(actionCode);
				int start = getStartIndex();
				state = new FileManager(conf).listFile(start);
				break;

		}

		return state.toJSONString();

	}

	public int getStartIndex() {

		String start = request.getParameter("start");

		try {
			return Integer.parseInt(start);
		} catch (Exception e) {
			return 0;
		}

	}

	/**
	 * callback参数验证
	 */
	public boolean validCallbackName(String name) {

		if (name.matches("^[a-zA-Z_]+[\\w0-9_]*$")) {
			return true;
		}

		return false;

	}

}
